#!/usr/bin/env python

import os, sys
import mad
import glob
import getpass
import gdata
import gdata.youtube.service
import math

developer_key = "AI39si7BsacKDuEdC91xBvNoov44fm_hGvr6EQAVX9LktyhnZhAilTMyhQ9OAAhkkebVs_BewtHpjkjzsrNz7KETSLr6DJhWTQ"
clientid = "emlynoregan"

def executecmd(cmdstring):
	print cmdstring
	os.system(cmdstring)
	
if (len(sys.argv) > 1):
	if sys.argv[1] == "--help":
		print ("Usage: %s [<vidpath> [<verb> [vidprefix [vidnamesuffixraw [vidnamesuffixdone]]]]]" % (sys.argv[0]))
		print "	where verb=upload|uploadonly|noverb|uploadnoverb"
		exit(2)
	else:
		path = sys.argv[1]
else:
	path = '.'

uploadonly = False
noverb = False
if (len(sys.argv) > 2) and (sys.argv[2] == "upload"):
	print "a"
	upload = True	
elif (len(sys.argv) > 2) and (sys.argv[2] == "uploadonly"):
	print "b"
	uploadonly = True
	upload = True
elif (len(sys.argv) > 2) and (sys.argv[2] == "uploadnoverb"):
	print "c"
	upload = True
	noverb = True
elif (len(sys.argv) > 2) and (sys.argv[2] == "noverb"):
	print "d"
	upload = False
	noverb = True
elif (len(sys.argv) > 2) and (sys.argv[2] == "verb"):
	print "e"
	upload = False
	noverb = False
else:
	print "f"
	upload = False

if (len(sys.argv) > 3):
	vidprefix = sys.argv[3]	
else:
	vidprefix = ""

if (len(sys.argv) > 4):
	vidnamesuffixraw = sys.argv[4]	
else:
	vidnamesuffixraw = "raw"

if (len(sys.argv) > 5):
	vidnamesuffixdone = sys.argv[5]	
else:
	vidnamesuffixdone = "done"

print "vidnamesuffixraw:" + vidnamesuffixraw
print "vidnamesuffixdone:" + vidnamesuffixdone
 

if upload:
	password = getpass.getpass("Youtube Password: ")
	# login to check the password, fail script here if it's wrong
	yt_service = gdata.youtube.service.YouTubeService()
	yt_service.email = 'emlynoregan@gmail.com'
	yt_service.password = password
	yt_service.source = 'upload2youtube python'
	yt_service.developer_key = developer_key
	yt_service.client_id = clientid
	yt_service.ProgrammaticLogin() 

print "1"

if not uploadonly:
	paths = []
	for infile in glob.glob( os.path.join(path, ('*%s.mpg' % vidnamesuffixraw)) ):	
		paths.append(infile)
	for infile in glob.glob( os.path.join(path, ('*%s.MP4' % vidnamesuffixraw)) ):	
		paths.append(infile)

	for infile in paths:	
		# set filename
		print ("infile=" + infile)
		workingfileprefix = infile[0:len(infile)-7]
		rawfilesuffix = infile[len(infile)-7:len(infile)]
		print("workingfileprefix=" + workingfileprefix)

		# delete files which will be generated
		if (os.path.exists('%s%s.mp3' % (workingfileprefix, vidnamesuffixraw))):
			executecmd('rm %s%s.mp3' % (workingfileprefix, vidnamesuffixraw))

		# extract audio to *raw.mp3
		executecmd(('/home/emlyn/dev/vidscripts/extractaudio.py %s%s %s%s.mp3') % (workingfileprefix, rawfilesuffix, workingfileprefix, vidnamesuffixraw))	

		#determine length
		mp3name = ('%s%s.mp3' % (workingfileprefix, vidnamesuffixraw));
		mf = mad.MadFile(mp3name)
		track_length_in_milliseconds = mf.total_time()

		number_of_10min_chunks = math.ceil(track_length_in_milliseconds / 900000.0)
		print ("track_length_in_milliseconds=%u, number_of_10min_chunks=%s" % (track_length_in_milliseconds, number_of_10min_chunks))

		# split if longer than 10 mins
		if number_of_10min_chunks > 1:
			executecmd(('/home/emlyn/dev/vidscripts/splitforyoutube.py %s%s %u %s-%s-%s.mpg') % (workingfileprefix, rawfilesuffix, number_of_10min_chunks, workingfileprefix, "%s", vidnamesuffixraw))
		# delete files which will be generated
			executecmd('mv %s%s %s%s.split' % (workingfileprefix, rawfilesuffix, workingfileprefix, rawfilesuffix))
			executecmd('rm %s%s.mp3' % (workingfileprefix, vidnamesuffixraw))

		
	paths = []
	for infile in glob.glob( os.path.join(path, ('*%s.mpg' % vidnamesuffixraw)) ):	
		paths.append(infile)
	for infile in glob.glob( os.path.join(path, ('*%s.MP4' % vidnamesuffixraw)) ):	
		paths.append(infile)

	for infile in paths:	

		# set filename
		workingfileprefix = infile[0:len(infile)-7]
		rawfilesuffix = infile[len(infile)-7:len(infile)]
		print(workingfileprefix)

		#workingfileprefix = (workingfilename less 7 characters)
		if (os.path.exists('%s%s.mp3' % (workingfileprefix, vidnamesuffixdone))):
			executecmd('rm %s%s.mp3' % (workingfileprefix, vidnamesuffixdone))
		if (os.path.exists('%s%s.mpg' % (workingfileprefix, vidnamesuffixdone))):
			executecmd('rm %s%s.mpg' % (workingfileprefix, vidnamesuffixdone))
		if (os.path.exists('%s%s.wav' % (workingfileprefix, vidnamesuffixraw))):
			executecmd('rm %s%s.wav' % (workingfileprefix, vidnamesuffixraw))
	

		# extract audio to *raw.mp3
		if (not os.path.exists('%s%s.mp3' % (workingfileprefix, vidnamesuffixraw))):
			executecmd(('/home/emlyn/dev/vidscripts/extractaudio.py %s%s %s%s.mp3') % (workingfileprefix, rawfilesuffix, workingfileprefix, vidnamesuffixraw))	

		# audio processing:
		# 1 - Convert mp3 to wav
		executecmd('mpg123 -w %s%s.wav %s%s.mp3' % (workingfileprefix, vidnamesuffixraw, workingfileprefix, vidnamesuffixraw))


		# 2 - process the wav file
		if noverb:
			executecmd('sox %s%s.wav %s%s.wav norm -9 lowpass 6000 reverb 0 norm 0' % (workingfileprefix, vidnamesuffixraw, workingfileprefix, vidnamesuffixdone))
		else:
			executecmd('sox %s%s.wav %s%s.wav norm -9 lowpass 6000 reverb 50 norm 0' % (workingfileprefix, vidnamesuffixraw, workingfileprefix, vidnamesuffixdone))

		# 3 - Convert wav to mp3
		executecmd('lame %s%s.wav %s%s.mp3' % (workingfileprefix, vidnamesuffixdone, workingfileprefix, vidnamesuffixdone))

		# 4 - Convert MP4 to mpg
		executecmd('/home/emlyn/dev/vidscripts/convertmp4tompeg.py %s%s %s%s.mpg' % (workingfileprefix, rawfilesuffix, workingfileprefix, vidnamesuffixraw))

		# combine *done.mp3 with *raw.mpg to make *done.mpg
		executecmd(('/home/emlyn/dev/vidscripts/replaceaudio.py %s%s.mpg %s%s.mp3 %s%s.mpg') % (workingfileprefix, vidnamesuffixraw, workingfileprefix, vidnamesuffixdone, workingfileprefix, vidnamesuffixdone))


print "2"

# now upload if necessary
if upload:
	moviepath = "*%s.mpg" % (vidnamesuffixdone)
	print moviepath
	category = 'Music'


	paths = []
	for infile in glob.glob( moviepath ):	
		paths.append(infile)

	for infile in paths:	
		# login to youtube
		yt_service = gdata.youtube.service.YouTubeService()
		yt_service.email = 'emlynoregan@gmail.com'
		yt_service.password = password
		yt_service.source = 'upload2youtube python'
		yt_service.developer_key = developer_key
		yt_service.client_id = clientid
		yt_service.ProgrammaticLogin()

		infileprefix = infile.replace("%s.mpg" % vidnamesuffixdone, "")
		print infileprefix
		
		my_media_group = gdata.media.Group(
		  title=gdata.media.Title(text=("%s - %s") % (vidprefix, infileprefix)),
		  description=gdata.media.Description(description_type='plain',
		                              text='Automated upload'),
	  	  keywords=gdata.media.Keywords(text=category),
		  category=[gdata.media.Category(
		      text=category,
		      scheme='http://gdata.youtube.com/schemas/2007/categories.cat',
		      label=category)],
		  player=None
		)

		video_entry = gdata.youtube.YouTubeVideoEntry(media=my_media_group)

		video_file_location = infile

		print ("Beginning Upload of %s" % (video_file_location))

		new_entry = yt_service.InsertVideoEntry(video_entry, video_file_location)

		print ("Finished Upload of %s" % (video_file_location))

		upload_status = yt_service.CheckUploadStatus(new_entry)

		if upload_status is not None:
		  	print("Status: %s (%s)" % (upload_status[0], upload_status[1]))
		else:
			print ("Success.")

print "Done"



